#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>

//写文件
void test1(){
    umask(0);
    ssize_t fd = open("test.txt",O_WRONLY|O_CREAT,0644);
    if(fd < 0){
        perror("open");
        return;
    }

    const char* msg = "hello world!\n";
    int len = strlen(msg);
    int cnt = 5;
    int ret = 0;
    while(cnt--){
        ret = write(fd,msg,len);
    }
    printf("%d\n",ret);
    close(fd);
    return;
}

//void test2(){
//    umask(0);
//    int fd = open("test2.txt",O_WRONLY|O_CREAT,0644);
//    if(fd < 0){
//        perror("open");
//        return;
//    }
//    int count = 5;
//    const char* msg = "hello world!\n";
//    int len = strlen(msg);
//    while(count--){
//        write(fd,msg,len);
//    }
//    close(fd);
//    return;
//
//}


//读文件
void test2(){
    ssize_t fd = open("test.txt",O_RDONLY);
    if(fd < 0){
        perror("open");
        return;
    }
    
    char buffer[1024];
    const char* msg = "hello world!\n";
    
    while(1){
        ssize_t s = read(fd,buffer,strlen(msg));
        if(s > 0)
            printf("%s",buffer);
        else    
            break;
    } 
    return;

}

//文件重定向dup2()函数
void test3(){
    umask(0);
    int fd = open("test2.txt",O_CREAT | O_RDWR,0644);
    if(fd < 0){
        perror("open");
        return;
    }
    close(1);
    dup2(fd,1);
    while(1){
        char buffer[128] = {0};
        ssize_t s = read(0,buffer,sizeof(buffer) - 1);
        if(s < 0){
            perror("read"); 
            break;
        }
        printf("%s",buffer);
        fflush(stdout);
    }
    return;
}



int main(){
    //test1();
    //test2();
    test3();

    return 0;
}
